package com.homework.news

import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.StrictMode
import android.view.View
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL

class VideoActivity : AppCompatActivity(), View.OnClickListener {

    var home: Button? = null

    var video: Button? = null

    var my: Button? = null

    private var recyclerView: RecyclerView? = null

    private var videoRecyclerView: RecyclerView? = null

    private val items =  ArrayList<String>()

    private var videos: List<Video> = ArrayList<Video>()

    private val types = ArrayList<String>()

    private val baseUrl = "http://apis.juhe.cn/fapig/douyin/billboard?key=f40fae2d2820cda5a4fe16d18b2a715b&type="

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video)
        if (Build.VERSION.SDK_INT > 9) {
            val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
            StrictMode.setThreadPolicy(policy)
        }
        getView()
        home?.setOnClickListener(this)
        video?.setOnClickListener(this)
        my?.setOnClickListener(this)
        initItems()
        println("初始化导航栏数据")
        println(items.size)
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        recyclerView?.layoutManager = layoutManager
        val adapter = TopNavAdapter(items)
        recyclerView?.adapter = adapter
        adapter!!.setOnItemClickListener(object : TopNavAdapter.OnItemClickListener{
            override fun onItemClick(view: View, position: Int) {
                println("点击了" + items[position])
                val responseData = getHttpResult(baseUrl + types[position])
                videos = emptyList()
                if (responseData != null) {
                    if( types[position] == "hot_video"){
                        val jsonArray = JSONObject(responseData);
                        val result = jsonArray.get("result").toString()
                        //Log.i("result", result)
                        val list: List<Video> = parseJSONWithGSON(result)
                        videos = list
                        println("获得视频数据共${videos.size}条")
                        setRecycleView()
                    }else{
                        val jsonArray = JSONObject(responseData)
                        var results: JSONArray = jsonArray.get("result") as JSONArray
                        for (i in 0 until results.length()){
                            val result: JSONObject = results[i] as JSONObject
                            val videoListJSON = result.get("video_list")
                            val videoList: List<Video> = parseJSONWithGSON(videoListJSON.toString())
                            videos = videos + videoList
                        }
                        setRecycleView()
                    }
                } else {
                    println("数据获取失败")
                }
            }
        })
        val responseData = getHttpResult(baseUrl + types[0])
        videos = emptyList()
        if (responseData != null) {
            if( types[0] == "hot_video"){
                val jsonArray = JSONObject(responseData);
                val result = jsonArray.get("result").toString()
                //Log.i("result", result)
                val list: List<Video> = parseJSONWithGSON(result)
                videos = list
                println("获得视频数据共${videos.size}条")
                setRecycleView()
            }else{
                val jsonArray = JSONObject(responseData)
                var results: JSONArray = jsonArray.get("result") as JSONArray
                for (i in 0 until results.length()){
                    val result: JSONObject = results[i] as JSONObject
                    val videoListJSON = result.get("video_list")
                    val videoList: List<Video> = parseJSONWithGSON(videoListJSON.toString())
                    videos = videos + videoList
                }
                setRecycleView()
            }
        } else {
            println("数据获取失败")
        }
    }

    private fun getView(){
        recyclerView = findViewById(R.id.recyclerView)
        videoRecyclerView = findViewById(R.id.videoRecyclerView)
        home = findViewById(R.id.home)
        video = findViewById(R.id.video)
        my = findViewById(R.id.my)
    }

    private fun setRecycleView(){
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        videoRecyclerView?.layoutManager = layoutManager
        val adapter = VideoAdapter(videos)
        videoRecyclerView?.adapter = adapter
        adapter.setOnItemClickListener(object : VideoAdapter.OnItemClickListener{
            override fun onItemClick(view: View, position: Int) {
                val intent = Intent(this@VideoActivity, VideoDetailActivity::class.java)
                val video = videos[position]
                intent.putExtra("video", video)
                println("点击了" + video.title)
                startActivity(intent)
            }
        })
    }

    fun getHttpResult(urlStr: String?): String? {
        return try {
            val url = URL(urlStr)
            val connect = url.openConnection() as HttpURLConnection
            val input = connect.inputStream
            val `in` = BufferedReader(InputStreamReader(input))
            var line: String? = null
            println(connect.responseCode)
            val sb = StringBuffer()
            while (`in`.readLine().also { line = it } != null) {
                sb.append(line)
            }
            sb.toString()
        } catch (e: Exception) {
            println(e.toString())
            null
        }
    }

    private fun parseJSONWithGSON(jsonData: String): List<Video> {
        val gson = Gson()
        val typeOf = object : TypeToken<List<Video>>() {}.type
        val videoList = gson.fromJson<List<Video>>(jsonData, typeOf)
        println(videoList[1].title)
        return videoList;
    }

    private fun initItems(){
        items.add("热门")
        types.add("hot_video")
        items.add("搞笑")
        types.add("amusement_overall")
        items.add("游戏")
        types.add("game_console")
        items.add("美食")
        types.add("food_overall")
        items.add("汽车")
        types.add("car_overall")
        items.add("旅行")
        types.add("travel_overall")
        items.add("体育")
        types.add("sport_overall")
        items.add("二次元")
        types.add("cospa_overall")
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.home -> {
                var intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
            }
            R.id.video -> {
                var intent = Intent(this, VideoActivity::class.java)
                startActivity(intent)
            }
        }
    }

}